package com.yyn.pigeon.config.exceptionhandler;


import com.yyn.pigeon.config.R;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/*
统一异常处理类
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})  //配置类
@Slf4j
public class GlobalExceptionHander {
//    全局的异常
    @ExceptionHandler(Exception.class)
    public R error(Exception ex){
        ex.printStackTrace();
        return R.error().message("执行了全局异常");

    }
//    特定的 sql异常
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
@ResponseBody //把响应的数据用json格式
public R exceptionHandler(SQLIntegrityConstraintViolationException ex){
    log.error(ex.getMessage());
    if(ex.getMessage().contains("Duplicate entry")){
        String[] de=ex.getMessage().split(" ");
        String msg = de[2];
    }
    return R.error().message("未知错误");
}
    //    特定的 sql异常
    @ExceptionHandler(FeignException.class)
    @ResponseBody //把响应的数据用json格式
    public R JwtException(FeignException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("404")){
//            String[] de=ex.getMessage().split(" ");
//            String msg = de[2];
            return R.error().message("404 可能是token值过期了:"+ex.getMessage());
        }
        System.out.println(ex.getMessage());
        return R.error().message("未知错误");
    }
    //    自定义的异常类
    @ExceptionHandler(CustomException.class)
    @ResponseBody //把响应的数据用json格式
    public R customException(CustomException ex){
        log.error(ex.getMessage());
        return R.error().code(ex.getCode()).message(ex.getMsg());
    }
}
